package com.sac.approval.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sac.approval.domain.*;
import com.sac.approval.enums.CategoryEnum;
import com.sac.approval.service.ApprovalLineTemplateService;
import com.sac.approval.service.ApprovalQueryService;
import com.sac.approval.service.AttachmentService;
import com.sac.approval.service.DelegateMappingService;
import com.sac.approval.vo.ApprovalVO;
import com.sac.common.utils.R;
import com.sac.common.utils.ShiroUtils;
import com.sac.emp.domain.Employee;
import com.sac.emp.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title:审批查询相关
 * @author xiaodong
 * @date 2018年11月1日 上午10:54:04
 * @desc
 */
@RestController
@RequestMapping("/approval/query")
public class ApprovalQueryController {
    @Autowired
    private ApprovalQueryService approvalQueryService;

    @Autowired
    private EmpService empService;

    @Autowired
    private ApprovalLineTemplateService approvalLineTemplateService;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
	private DelegateMappingService delegateMappingService;

    @GetMapping("/getApproval/{appId}")
    public Object getApproval(@PathVariable String appId) {
        ApprovalDO approval = approvalQueryService.getApproval(appId);
        Employee emp = empService.getEmpDetailInfo(approval.getCreateUser());
        List<AttachmentDO> attachmentList = attachmentService.list(new HashMap<String,Object>(){{
            put("appId",appId);
        }});
        approval.setCreateUserNm(emp.getEmpNm());
        approval.setCreateUserJob(emp.getEmpJob());
        approval.setAttachmentList(attachmentList);

        return approval;
    }

    /**
     * 获取待审批人列表
     * @param appId
     * @return
     */
    @GetMapping("/getPendingApproverList/{appId}")
    public Object getPendingApproverList(@PathVariable String appId) {
        List<ApprovalLineDO> lineList = approvalQueryService.getPendingApproverList(appId);
        lineList.forEach(line->{
            Employee emp = empService.getEmpDetailInfo(line.getReceiverEpid());
            line.setReceiverName(emp.getEmpNm());
        });
        PageInfo<ApprovalLineDO> pageInfo = new PageInfo<>(lineList);
        return pageInfo;
    }

    /**
     * 验证是否可取消提交
     * @param appId
     * @return
     */
    @GetMapping("/validateCancelSubmission/{appId}")
    public Object validateCancelSubmission(@PathVariable String appId) {
        ApprovalLineDO line = approvalQueryService.getFirstApprovalLine(appId);
        if(line!=null){
            return line.getStatus()==0;
        }
        return false;
    }

    /**
     * 验证用户密码
     * @param pwd
     * @return
     */
    @GetMapping("/validatePassword/{pwd}")
    public Object validatePassword(@PathVariable String pwd) {
        return pwd == pwd;
    }

    @GetMapping("/getPostponed/{appTemplateId}")
    public Object getPostponed(@PathVariable String appTemplateId) {
        ApprovalTemplateDO draft = approvalQueryService.getApprovalTemplate(appTemplateId);
        List<ApprovalLineTemplateDO> lineTemplateList = approvalLineTemplateService.list(new HashMap<String,Object>(){{
            put("appTemplateId",appTemplateId);
        }});
        lineTemplateList.forEach(line->{
            Employee emp = empService.getEmpDetailInfo(line.getReceiverEpid());
            line.setReceiverName(emp.getEmpNm());
            line.setReceiverJob(emp.getEmpJob());
        });
        List<AttachmentDO> attachments = attachmentService.list(new HashMap<String,Object>(){{
            put("appTemplateId",appTemplateId);
        }});
        draft.setLineTemplateList(lineTemplateList);
        draft.setAttachmentList(attachments);
        return draft;
    }

    /**
     * 查询审批路径
     * @param params
     * @return
     */
    @GetMapping("/listLines")
    public PageInfo<ApprovalLineDO> listLines(@RequestParam Map<String, Object> params) {
        List<ApprovalLineDO> lineList = approvalQueryService.listLines(params);
        lineList.forEach(line->{
            Employee emp = empService.getEmpDetailInfo(line.getReceiverEpid());

            line.setReceiverName(emp.getEmpNm());
            line.setReceiverJob(emp.getEmpJob());
            line.setReceiverDeptNm(emp.getHrDeptNm());

            DelegateMappingDO agent = delegateMappingService.getValidDelegate(line.getReceiverEpid());
            line.setAgent(agent);
        });
        PageInfo<ApprovalLineDO> pageInfo = new PageInfo<>(lineList);
        return pageInfo;
    }

    /**
     * 待审批
     * @param params
     * @return
     */
    @GetMapping("/listPending")
    public PageInfo<ApprovalVO> listPending(@RequestParam Map<String, Object> params) {
        params.put("receiverEpid", ShiroUtils.getEmpId());

        String resultVal = params.get("createUser")== null ? "" : params.get("createUser").toString();
        if(!resultVal.equals("")){
            Employee emp = empService.getEmpDetailInfoByName(resultVal);
            if(emp != null) {
                params.put("createUser", emp.getEmpId());
            }
        }

        PageHelper.startPage(params);
        List<ApprovalVO> pendingList = approvalQueryService.listPending(params);
        pendingList.forEach(approval->{
            approval.setCategory(CategoryEnum.getCategoryColor(Integer.parseInt(approval.getCategory()==null ? "0" : approval.getCategory())));
            Employee empDetailInfo = empService.getEmpDetailInfo(approval.getCreateUser());
            approval.setCreateUserNm(empDetailInfo.getEmpNm());
        });
        PageInfo<ApprovalVO> pageInfo = new PageInfo<>(pendingList);
        return pageInfo;
    }

    @GetMapping("/getPendingNotReadCount")
    public R getPendingNotReadCount(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("receiverEpid", ShiroUtils.getEmpId());
        int count = approvalQueryService.getPendingNotReadCount(params);
        return R.ok().put("count",count);
    }

    /**
     * 已提交列表
     * @param params
     * @return
     */
    @GetMapping("/listSubmission")
    public PageInfo<ApprovalDO> listSubmission(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("createUser", ShiroUtils.getEmpId());

        PageHelper.startPage(params);
        List<ApprovalDO> submissionList = approvalQueryService.listSubmission(params);
        submissionList.forEach(approval->{
            approval.setCategory(CategoryEnum.getCategoryColor(Integer.parseInt(approval.getCategory()==null? "0" : approval.getCategory())));
            List<ApprovalLineDO> lineList = approvalQueryService.getPendingApproverList(approval.getAppId());
            if(lineList!=null && lineList.size()>0){
                Employee emp = empService.getEmpDetailInfo(lineList.get(0).getReceiverEpid());
                if(lineList.size()>1){
                    approval.setPendingApprover(emp.getEmpNm()+"(+1)");
                }else{
                    approval.setPendingApprover(emp.getEmpNm());
                }
            }
        });

        PageInfo<ApprovalDO> pageInfo = new PageInfo<>(submissionList);
        return pageInfo;
    }

    /**
     * 草稿箱
     * @param params
     * @return
     */
    @GetMapping("/listPostponed")
    public PageInfo<ApprovalTemplateDO> listPostponed(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("createUser",ShiroUtils.getEmpId());
        params.put("dot","D");

        PageHelper.startPage(params);
        List<ApprovalTemplateDO> postponedList = approvalQueryService.listPostponed(params);
        postponedList.forEach(approvalTemplate->{
            Employee emp = empService.getEmpDetailInfo(approvalTemplate.getCreateUser());
            approvalTemplate.setCreateUserNm(emp.getEmpNm());
        });
        PageInfo<ApprovalTemplateDO> pageInfo = new PageInfo<>(postponedList);
        return pageInfo;
    }

    /**
     * 预览审批
     * @param params
     * @return
     */
    @GetMapping("/listPreliminary")
    public PageInfo<ApprovalVO> listPreliminary(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("receiverEpid",ShiroUtils.getEmpId());

        String resultVal = params.get("createUser")== null ? "" : params.get("createUser").toString();
        if(!resultVal.equals("")){
            Employee emp = empService.getEmpDetailInfoByName(resultVal);
            if(emp != null) {
                params.put("createUser", emp.getEmpId());
            }
        }

        PageHelper.startPage(params);
        List<ApprovalVO> preliminaryList = approvalQueryService.listPreliminary(params);
        preliminaryList.forEach(approval->{
            approval.setCategory(CategoryEnum.getCategoryColor(Integer.parseInt(approval.getCategory()==null? "0" : approval.getCategory())));
            Employee emp = empService.getEmpDetailInfo(approval.getCreateUser());
            approval.setCreateUserNm(emp.getEmpNm());
        });
        PageInfo<ApprovalVO> pageInfo = new PageInfo<>(preliminaryList);
        return pageInfo;
    }

    /**
     * 已审批
     * @param params
     * @return
     */
    @GetMapping("/listApproved")
    public PageInfo<ApprovalVO> listApproved(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("receiverEpid",ShiroUtils.getEmpId());

        String resultVal = params.get("createUser")== null ? "" : params.get("createUser").toString();
        if(!resultVal.equals("")){
            Employee emp = empService.getEmpDetailInfoByName(resultVal);
            if(emp != null) {
                params.put("createUser", emp.getEmpId());
            }
        }

        PageHelper.startPage(params);
        List<ApprovalVO> approvedList = approvalQueryService.listApproved(params);
        approvedList.forEach(approval->{
            approval.setCategory(CategoryEnum.getCategoryColor(Integer.parseInt(approval.getCategory()==null? "0" : approval.getCategory())));
            Employee emp = empService.getEmpDetailInfo(approval.getCreateUser());
            approval.setCreateUserNm(emp.getEmpNm());
        });
        PageInfo<ApprovalVO> pageInfo = new PageInfo<>(approvedList);
        return pageInfo;
    }

    /**
     * 通知列表
     * @param params
     * @return
     */
    @GetMapping("/listNotification")
    public PageInfo<ApprovalVO> listNotification(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("receiverEpid",ShiroUtils.getEmpId());

        String resultVal = params.get("createUser")== null ? "" : params.get("createUser").toString();
        if(!resultVal.equals("")){
            Employee emp = empService.getEmpDetailInfoByName(resultVal);
            if(emp != null) {
                params.put("createUser", emp.getEmpId());
            }
        }

        PageHelper.startPage(params);
        List<ApprovalVO> notificationList = approvalQueryService.listNotification(params);
        notificationList.forEach(approval->{
            approval.setCategory(CategoryEnum.getCategoryColor(Integer.parseInt(approval.getCategory()==null? "0" : approval.getCategory())));
            Employee emp = empService.getEmpDetailInfo(approval.getCreateUser());
            approval.setCreateUserNm(emp.getEmpNm());
        });
        PageInfo<ApprovalVO> pageInfo = new PageInfo<>(notificationList);
        return pageInfo;
    }


    @GetMapping("/listDelegateMapping")
    public Object listDelegateMapping(@RequestParam Map<String, Object> params) {
        params.put("userId",ShiroUtils.getEmpId().toString());
        List<DelegateMappingDO> list = delegateMappingService.list(params);
        return R.ok().put("result",list.size()>0 ? list.get(0) : null);
    }

}
